<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\MerchantAudit as MerchantAuditModel;
use think\Db;

/**
 * 商家认证审核管理
 *
 * @icon fa fa-check-square
 */
class MerchantAudit extends Backend
{
    protected $model = null;
    protected $searchFields = 'merchant_id,store_name,store_phone';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new MerchantAuditModel();
    }

    /**
     * 查看审核列表
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            // 构建状态筛选下拉选项
            $this->view->assign('statusList', [
                '' => __('全部'),
                '0' => __('待审核'),
                '1' => __('审核中'),
                '2' => __('审核通过'),
                '3' => __('审核不通过')
            ]);
            return $this->view->fetch();
        }
        
        try {
            // 手动获取请求参数
            $page = $this->request->param('page', 1);
            $limit = $this->request->param('limit', 10);
            $search = $this->request->param('search', '');
            $sort = $this->request->param('sort', 'id');
            $order = $this->request->param('order', 'desc');
            $verification_status = $this->request->param('verification_status', '');
            
            // 构建查询条件
            $where = [];
            
            // 搜索条件
            if (!empty($search)) {
                $where[] = ['merchant_id|store_name|store_phone', 'like', '%' . $search . '%'];
            }
            
            // 审核状态筛选
            if ($verification_status !== '') {
                $where[] = ['verification_status', '=', $verification_status];
            }
            
            // 查询数据
            $list = Db::name('merchant_audit')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            
            // 处理状态显示
            $items = $list->items();
            foreach ($items as &$item) {
                switch ($item['verification_status']) {
                    case 0:
                        $item['verification_status_text'] = '待审核';
                        break;
                    case 1:
                        $item['verification_status_text'] = '审核中';
                        break;
                    case 2:
                        $item['verification_status_text'] = '审核通过';
                        break;
                    case 3:
                        $item['verification_status_text'] = '审核不通过';
                        break;
                    default:
                        $item['verification_status_text'] = '未知状态';
                }
                
                // 格式化时间
                if (isset($item['created_at']) && $item['created_at']) {
                    $item['created_at'] = date('Y-m-d H:i:s', $item['created_at']);
                }
                if (isset($item['updated_at']) && $item['updated_at']) {
                    $item['updated_at'] = date('Y-m-d H:i:s', $item['updated_at']);
                }
            }
            
            $result = ['total' => $list->total(), 'rows' => $items];
            return json($result);
            
        } catch (\Exception $e) {
            return json(['total' => 0, 'rows' => [], 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 查看详情
     */
    public function detail($ids = null)
    {
        $row = Db::name('merchant_audit')->where('id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 审核操作
     */
    public function audit($ids = null)
    {
        $row = Db::name('merchant_audit')->where('id', $ids)->find();
        
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost() || $this->request->isAjax()) {
            $params = $this->request->post("row/a");
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            
            // 开启事务
            Db::startTrans();
            try {
                // 更新审核状态
                $result = Db::name('merchant_audit')
                    ->where('id', $ids)
                    ->update([
                        'verification_status' => $params['verification_status'],
                        'reject_reason' => isset($params['reject_reason']) ? $params['reject_reason'] : '',
                        'audit_time' => time(),
                        'auditor' => $this->auth->nickname, // 添加审核人信息
                        'updated_at' => time() 
                    ]);
                
                if ($result === false) {
                    throw new Exception('更新审核状态失败');
                }
                
                // 如果审核通过，同步数据到商家主表
                if ($params['verification_status'] == 2) {
                    // 只更新商家表的审核状态
                    $merchantResult = Db::name('merchant')
                        ->where('merchant_id', $row['merchant_id'])
                        ->update([
                            'verification_status' => 1, // merchant表中1表示认证通过
                            'updated_at' => time(),
                        ]);
                        
                    if ($merchantResult === false) {
                        throw new Exception('更新商家审核状态失败');
                    }
                    
                } elseif ($params['verification_status'] == 3) {
                    // 如果审核不通过，只更新商家表的审核状态
                    $merchantResult = Db::name('merchant')
                        ->where('merchant_id', $row['merchant_id'])
                        ->update([
                            'verification_status' => 2, // merchant表中2表示认证失败
                            'updated_at' => time(),
                        ]);
                        
                    if ($merchantResult === false) {
                        throw new Exception('更新商家审核状态失败');
                    }
                }
                
                // 提交事务
                Db::commit();
                $this->success();
                
            } catch (Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        
        $this->view->assign("row", $row);
        $this->view->assign('statusList', [
            '2' => __('审核通过'),
            '3' => __('审核不通过')
        ]);
        return $this->view->fetch();
    }
}